package com.atguigu.dga.thread;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class ThreadDemo4 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        /*
        Future的使用
         */
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        //准备集合，用于接收每一个线程返回的结果
        CompletableFuture<Integer>[] result = new CompletableFuture[10];

        for (int i = 0; i < 10; i++) {

            //等Future可以get到结果
            int finalI = i;

            /*
            运行一个线程，执行Supplier中的逻辑
            运行结束后，会把返回值，赋值给result数组中指定的位置
             */
            CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    //耗时操作
                    try{
                        Thread.sleep(3000);
                    }catch (Exception e){
                        throw new RuntimeException(e);
                    }
                    System.out.println(finalI + "表已经考核完毕！");
                    return finalI;
                }
            },executorService);
        }

        //如何知道那些线程都已经运行完毕 会阻塞，等result中所有的Future都已经兑现
        CompletableFuture.allOf(result).join();

        //运行到这一行，所有的Future都已经交割，获取结果
        List<Integer> resultList = Arrays.stream(result)
                .map(future -> future.join())
                .collect(Collectors.toList());

        System.out.println("以下编号的线程：" + resultList + "，全部运行结束！");
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));

        executorService.shutdown();
    }
}
